package com.yuyang.springcloud.mylb;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yu yang
 * @date 2022/10/26 -20:06
 */
@Component
@Slf4j
public class MyLB implements LoadBalanced {
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    private Integer INTEGER_MAX_VALUE = Integer.MAX_VALUE;

    private final int incrementAndGet() {
        int current;
        int next;
        for(;;){
            current = this.atomicInteger.get();
            next = current >= INTEGER_MAX_VALUE ? 0 : current + 1;
            if (atomicInteger.compareAndSet(current,next)){
                log.info("*****第{}次轮询",next);
                return next;
            }
        }
    }

    //负载均衡算法 rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标  ，每次服务重启动后rest接口计数从1开始。
    @Override
    public ServiceInstance getServerInstance(List<ServiceInstance> serviceInstanceList) {
        int next = incrementAndGet();
        int index = next % serviceInstanceList.size();
        return serviceInstanceList.get(index);
    }
}
